package com.lzx.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.reggie.common.CustomException;
import com.lzx.reggie.dto.SetmealDto;
import com.lzx.reggie.entity.Setmeal;
import com.lzx.reggie.entity.SetmealDish;
import com.lzx.reggie.service.SetmealDishService;
import com.lzx.reggie.service.SetmealService;
import com.lzx.reggie.mapper.SetmealMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author 86176
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2024-07-11 15:15:28
 */
@Service
@RequiredArgsConstructor
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {

    private final SetmealDishService setmealDishService;

    @Value("${reggie.path}")
    private String basePath;

    //新增套餐，同时保存套餐和菜品的关联方法
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息，setmeal--insert
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }

        //保存套餐和菜品的关联信息，setmeal_dish--insert
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐时，把菜品关联的数据也一并删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //1.1查询状态，判断是否启售
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        //1.2 如果不能删除，抛出异常
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖中，不能删除...");
        }

        //2.删除套餐表中的数据--setmeal
        this.removeByIds(ids);

        //3.删除关系表中的数据--setmeal——dish
        //delete from setmeal_dish where setmeal_id in(ids)
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper1);

    }
}




